package com.sunny.webflux.handler;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @author sunny
 * @date 2018/11/30
 */
@Component
public class TimeHandler {

    /**
     * 返回date格式的日期字符串
     *
     * @param request
     * @author sunny
     * @date 2018/11/30
     * @return reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>
     */
    public Mono<ServerResponse> getDate(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_PLAIN).body(Mono.just("Now is " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())), String.class);
    }

    /**
     * 返回dateTime格式的日期字符串
     *
     * @param request
     * @author sunny
     * @date 2018/11/30
     * @return reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>
     */
    public Mono<ServerResponse> getDateTime(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_PLAIN).body(Mono.just("Now is " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())), String.class);
    }

    /**
     * 每秒返回一次时间
     *  TEXT_EVENT_STREAM：表示Content-Type为text/event-stream 即SSE（服务端推送）
     *  Flux.interval：利用interval生成每秒一个数据的流
     * @param request
     * @author sunny
     * @date 2018/11/30
     * @return reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>
     */
    public Mono<ServerResponse> sendTimePerSec(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_EVENT_STREAM).body(Flux.interval(Duration.ofSeconds(1)).map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())), String.class);
    }
}
